//
//  IGTimeEditVC.m
//  jingdongfang
//
//  Created by MTiMac01 on 2017/11/17.
//  Copyright © 2017年 LJL. All rights reserved.
//

#import "IGTimeEditVC.h"
#import "IGPowerTimeApi.h"
#import "IGTimeRepetitionVC.h"


@interface IGTimeEditVC ()<UITableViewDelegate, UITableViewDataSource, UIPickerViewDelegate, UIPickerViewDataSource>
{
    UIPickerView *picker;
    BOOL isOnTime;
}
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) IGPowerTimeApi *api;
@property (nonatomic, strong) IGTimeSwitch *model;

@end

@implementation IGTimeEditVC

- (instancetype)initWithModel:(IGTimeSwitch *)model
{
    self = [super init];
    if (self)
    {
        self.model = model;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor mainBackgroundColor];
    self.api = [IGPowerTimeApi new];
//    self.title = @"编辑时间";
    self.title = NSLocalizedString(@"Edit the Time", nil);
    [self.view addSubview:self.tableView];
//    [self ig_setupRightButtonItemWithTitle:@"确定" image:nil highLightedImage:nil];
    [self ig_setupRightButtonItemWithTitle:NSLocalizedString(@"Confirm", nil) image:nil highLightedImage:nil];

    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(0);
    }];
    [self showMune];
}

- (void)ig_rightButtonPressed:(id)sender
{
    _api.macId = _model.macId;
    _api.groupStr = _model.group;
    _api.switchsArr = _model.switchs;
    _api.onTimeStr = _model.onTime;
    _api.offTimeStr = _model.offTime;
    _api.typeStr = _model.type;
    [_api startWithDecodeClass:[IGPowerTimeResp class] CompletionBlockWithSuccess:^(id responseObject, NSError *error) {
        if (responseObject)
        {
            [self.navigationController popViewControllerAnimated:YES];
//            [self presentMessageTips:@"修改成功"];
            [self presentMessageTips:NSLocalizedString(@"Change Successfully", nil)];
        }
    }];
}
- (UITableView *)tableView
{
    if (!_tableView)
    {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorInset = UIEdgeInsetsMake(0, -100, 0, 0);
    }
    return _tableView;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0)
    {
        return 2;
    }
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50.0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0)
    {
        return 10.0;
    }
    return 5.0;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 0)
    {
        if (indexPath.row == 0)
        {
            isOnTime = YES;
            [self showAction];
        }
        else if (indexPath.row == 1)
        {
            isOnTime = NO;
            [self showAction];
        }
    }
    else if (indexPath.section == 1)
    {
        IGTimeRepetitionVC *vc = [[IGTimeRepetitionVC alloc] initWithModel:self.model];
        vc.block = ^(IGTimeSwitch *model) {
            self.model = _model;
            [self.tableView reloadData];
        };
        [UIViewController ig_pushViewController:vc animated:YES];
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellID = @"IGScreenModelVCID";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (!cell)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellID];
    }
    cell.textLabel.font = [UIFont font16];
    cell.textLabel.textColor = [UIColor c4Color];
    cell.detailTextLabel.textColor = [UIColor c5Color];
    cell.detailTextLabel.font = [UIFont font16];
    
    if (indexPath.section == 0)
    {
        if (indexPath.row == 0)
    {
//        cell.textLabel.text = @"开机时间";
        cell.textLabel.text = NSLocalizedString(@"ON Time", nil);
        NSMutableString *onTime = [NSMutableString stringWithString:_model.onTime];
        [onTime insertString:@":" atIndex:2];
        cell.detailTextLabel.text = onTime;
    }
    else if (indexPath.row == 1)
    {
//        cell.textLabel.text = @"关机时间";
        cell.textLabel.text = NSLocalizedString(@"OFF Time", nil);
        NSMutableString *offTime = [NSMutableString stringWithString:_model.offTime];
        [offTime insertString:@":" atIndex:2];
        cell.detailTextLabel.text = offTime;
    }
    }
    else if (indexPath.section == 1)
    {
//        cell.textLabel.text = @"重复";
        cell.textLabel.text = NSLocalizedString(@"Repeat", nil);
        if ([_model.type isEqualToString:@"0"])
        {
//            cell.detailTextLabel.text = @"每天";
            cell.detailTextLabel.text = NSLocalizedString(@"Daily", nil);
        }
        else if ([_model.type isEqualToString:@"1"])
        {
//            cell.detailTextLabel.text = @"工作日";
            cell.detailTextLabel.text = NSLocalizedString(@"Working Day", nil);
        }
        else if ([_model.type isEqualToString:@"2"])
        {
//            cell.detailTextLabel.text = @"周末";
            cell.detailTextLabel.text = NSLocalizedString(@"Weekend", nil);
        }
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    return cell;
}

#pragma mark - UIPickerViewDataSource, UIPickerViewDelegate

#pragma mark - showMune

- (void)showMune
{
    UIControl *ctrl = [[UIControl alloc] initWithFrame:CGRectMake(0, 0, KSCREENWIDTH, KSCREENHEIGHT)];
    ctrl.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.7];
    ctrl.tag = 868;
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, KSCREENHEIGHT-250, KSCREENWIDTH, 250)];
    view.backgroundColor = [UIColor whiteColor];
    CGFloat height = [self createSubview:view];
    view.height = height;
    view.y = KSCREENHEIGHT-height;
    [ctrl addSubview:view];
    [ctrl addTarget:self action:@selector(ctrlAction:) forControlEvents:UIControlEventTouchUpInside];
    [[UIApplication sharedApplication].keyWindow addSubview:ctrl];
    ctrl.alpha = 0;
}

- (CGFloat)createSubview:(UIView *)view
{
    UIView *nav = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KSCREENWIDTH, 44)];
    nav.backgroundColor = [UIColor whiteColor];
    [view addSubview:nav];
    
    UIButton *left = [UIButton buttonWithType:UIButtonTypeCustom];
    left.frame = CGRectMake(10, 0, 50, 44);
    left.titleLabel.font = [UIFont systemFontOfSize:16];
//    [left setTitle:@"取消" forState:UIControlStateNormal];
    [left setTitle:NSLocalizedString(@"Cancel", nil) forState:UIControlStateNormal];
    [left setTitleColor:[UIColor appColor] forState:UIControlStateNormal];
    [left addTarget:self action:@selector(cancelAction:) forControlEvents:UIControlEventTouchUpInside];
    [nav addSubview:left];
    
    UIButton *right = [UIButton buttonWithType:UIButtonTypeCustom];
    right.frame = CGRectMake(KSCREENWIDTH-60, 0, 50, 44);
    right.titleLabel.font = [UIFont systemFontOfSize:16];
//    [right setTitle:@"确定" forState:UIControlStateNormal];
    [right setTitle:NSLocalizedString(@"Confirm", nil) forState:UIControlStateNormal];
    [right setTitleColor:[UIColor appColor] forState:UIControlStateNormal];
    [right addTarget:self action:@selector(doneAction:) forControlEvents:UIControlEventTouchUpInside];
    [nav addSubview:right];
    if (!picker)
    {
        picker = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 44, KSCREENWIDTH, view.height-44)];
        picker.backgroundColor = [UIColor whiteColor];
        picker.delegate = self;
        picker.dataSource = self;
        picker.showsSelectionIndicator = YES;
    }
    [view addSubview:picker];
    return picker.height+44;
}

- (void)showAction
{
    NSString *time = @"";
    if (isOnTime)
    {
        time = _model.onTime;
    }
    else
    {
        time = _model.offTime;
    }
    [picker selectRow:[[time substringToIndex:2] integerValue] inComponent:0 animated:YES];
    [picker selectRow:[[time substringFromIndex:2] integerValue] inComponent:1 animated:YES];
    [self showCtrl];
}


- (void)ctrlAction:(UIControl *)ctrl
{
    [self hiddenCtrl];
}

- (void)cancelAction:(UIButton *)btn
{
    [self hiddenCtrl];
}

- (void)showCtrl
{
    UIControl *ctrl = [[UIApplication sharedApplication].keyWindow viewWithTag:868];
    [UIView animateWithDuration:.2 animations:^{
        ctrl.alpha = 1;
        picker.alpha = 1;
    }];
}

- (void)hiddenCtrl
{
    UIControl *ctrl = [[UIApplication sharedApplication].keyWindow viewWithTag:868];
    [UIView animateWithDuration:.2 animations:^{
        ctrl.alpha = 0;
    }];
}

- (void)doneAction:(UIButton *)btn
{
    NSString *str1 = [NSString stringWithFormat:@"%02ld",[picker selectedRowInComponent:0]];
    NSString *str2 = [NSString stringWithFormat:@"%02ld",[picker selectedRowInComponent:1]];
    NSString *str = [str1 stringByAppendingString:str2];
    if (isOnTime)
    {
        _model.onTime = str;
    }
    else
    {
        _model.offTime = [str1 stringByAppendingString:str2];
    }
    [UIView animateWithDuration:.2 animations:^{
        picker.alpha = 0;
    }];
    [self.tableView reloadData];
    [self hiddenCtrl];
}

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 2;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    if (component == 0)
    {
        return 24;
    }
    return 60;
}

- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component
{
    return 35;
}

- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)componen
{
    return 60;
}

//- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
//{
//    UILabel *text = [[UILabel alloc] initWithFrame:CGRectZero];
//    text.font = [UIFont boldSystemFontOfSize:20];
//    text.text = [NSString stringWithFormat:@"%02ld", row];
//    [text sizeToFit];
//    return text;
//}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    if (pickerView == picker)
    {
        return [NSString stringWithFormat:@"%02ld", row];
    }
    return nil;
}

- (void)dealloc
{
    [picker removeFromSuperview];
    picker = nil;
    UIControl *ctrl = [[UIApplication sharedApplication].keyWindow viewWithTag:868];
    [ctrl removeFromSuperview];
    ctrl = nil;

}
@end
